package com.ashley.phonemsn

import androidx.lifecycle.ViewModel
import androidx.lifecycle.viewModelScope
import kotlinx.coroutines.flow.MutableStateFlow
import kotlinx.coroutines.flow.StateFlow
import kotlinx.coroutines.flow.asStateFlow
import kotlinx.coroutines.launch

/**
 * SMS功能相关的ViewModel
 */
class SmsViewModel : ViewModel() {
    
    // 当前对话的手机号码
    private val _currentPhoneNumber = MutableStateFlow("10086")
    val currentPhoneNumber: StateFlow<String> = _currentPhoneNumber.asStateFlow()
    
    // 当前联系人名称
    private val _currentContactName = MutableStateFlow("中国移动客服")
    val currentContactName: StateFlow<String> = _currentContactName.asStateFlow()
    
    // 存储电话号码到联系人名称的映射
    private val _contactNames = MutableStateFlow(mutableMapOf("10086" to "中国移动客服"))
    val contactNames: StateFlow<Map<String, String>> = _contactNames.asStateFlow()
    
    // 当前对话的消息列表
    private val _currentMessages = MutableStateFlow<List<Message>>(emptyList())
    val currentMessages: StateFlow<List<Message>> = _currentMessages.asStateFlow()
    
    // 存储所有电话号码的消息历史
    private val _messageHistory = mutableMapOf<String, List<Message>>()
    
    // 已保存的电话号码列表
    private val _savedPhoneNumbers = MutableStateFlow(mutableSetOf("10086"))
    val savedPhoneNumbers: StateFlow<Set<String>> = _savedPhoneNumbers.asStateFlow()
    
    // 消息ID计数器
    private var messageIdCounter = 0

    /**
     * 更新当前对话的手机号码
     */
    fun updatePhoneNumber(number: String, contactName: String? = null) {
        viewModelScope.launch {
            // 保存当前对话的消息历史
            val currentNumber = _currentPhoneNumber.value
            if (currentNumber.isNotEmpty()) {
                _messageHistory[currentNumber] = _currentMessages.value
            }
            
            // 立即更新当前电话号码
            _currentPhoneNumber.value = number
            
            // 创建一个新的mutableMap来更新联系人名称映射，确保UI能够检测到变化
            val updatedContactNames = _contactNames.value.toMutableMap()
            if (contactName != null) {
                updatedContactNames[number] = contactName
                _contactNames.value = updatedContactNames
                _currentContactName.value = contactName
            } else {
                // 如果没有提供联系人名称，尝试从已有映射中获取
                _currentContactName.value = updatedContactNames.getOrDefault(number, number)
            }
            
            // 创建一个新的mutableSet来更新已保存的电话号码列表
            val updatedSavedNumbers = _savedPhoneNumbers.value.toMutableSet()
            if (number.isNotEmpty()) {
                updatedSavedNumbers.add(number)
                _savedPhoneNumbers.value = updatedSavedNumbers
            }
            
            // 加载新电话号码的消息历史，如果没有则显示空列表
            _currentMessages.value = _messageHistory.getOrDefault(number, emptyList())
        }
    }

    /**
     * 添加消息到当前对话
     */
    fun addMessage(message: Message) {
        viewModelScope.launch {
            val currentList = _currentMessages.value.toMutableList()
            currentList.add(message)
            _currentMessages.value = currentList
            
            // 同时更新消息历史
            val currentNumber = _currentPhoneNumber.value
            if (currentNumber.isNotEmpty()) {
                _messageHistory[currentNumber] = currentList
            }
        }
    }

    /**
     * 获取新的消息ID
     */
    fun getNewMessageId(): Int {
        return ++messageIdCounter
    }
    
    /**
     * 清空当前对话的消息
     */
    fun clearMessages() {
        viewModelScope.launch {
            _currentMessages.value = emptyList()
            
            // 同时更新消息历史
            val currentNumber = _currentPhoneNumber.value
            if (currentNumber.isNotEmpty()) {
                _messageHistory[currentNumber] = emptyList()
            }
        }
    }
    
    /**
     * 获取指定手机号码的消息历史
     */
    fun getMessagesForNumber(phoneNumber: String): List<Message> {
        return _messageHistory.getOrDefault(phoneNumber, emptyList())
    }
    
    /**
     * 删除指定的电话号码及其消息历史
     */
    fun deletePhoneNumber(phoneNumber: String) {
        viewModelScope.launch {
            _messageHistory.remove(phoneNumber)
            
            // 创建新的mutableSet来更新已保存的电话号码列表
            val updatedSavedNumbers = _savedPhoneNumbers.value.toMutableSet()
            updatedSavedNumbers.remove(phoneNumber)
            _savedPhoneNumbers.value = updatedSavedNumbers
            
            // 如果删除的是当前号码，切换到第一个保存的号码或默认号码
            if (phoneNumber == _currentPhoneNumber.value) {
                if (updatedSavedNumbers.isNotEmpty()) {
                    updatePhoneNumber(updatedSavedNumbers.first())
                } else {
                    _currentPhoneNumber.value = ""
                    _currentMessages.value = emptyList()
                }
            }
        }
    }
}